
package com.tools.cleanmaster.model.db;

import com.tools.cleanmaster.utils.Base64;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class DataBaseDESUtil {


    private static final int ENCRYPT = 1;

    private static final int DECRYPT = 2;

    private static final String DES_ALGORITHM="DES";

    private static final String UTF8= "UTF8";

    /**
     * 根据参数生成 KEY
     */
    private static SecretKey getKey(String secretKey) throws NoSuchAlgorithmException,
            InvalidKeyException, InvalidKeySpecException {

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
        DESKeySpec keySpec = new DESKeySpec(secretKey.getBytes());
        return keyFactory.generateSecret(keySpec);
    }

    /**
     * 加密 String 明文输入 ,String 密文输出
     */
    public static String encryptStr(String strEncrypt, String key) {
        byte[] enData = null;
        byte[] enByte = null;
        String enStr = "";
        try {
            enByte = strEncrypt.getBytes(UTF8);
            enData = encryptOrDecryptByte(enByte, ENCRYPT, key);
            enStr = Base64.encode(enData);

        } catch (Exception e) {
        } finally {
            enByte = null;
            enData = null;
        }
        return enStr;
    }

    /**
     * 解密 以 String 密文输入 ,String 明文输出
     * @param strMi
     * @return
     */
    public static String decryptStr(String strDecrypt, String key) {
        byte[] deData = null;
        byte[] deByte = null;
        String deStr = "";
        try {
            deByte = Base64.decode(strDecrypt);
            deData = encryptOrDecryptByte(deByte, DECRYPT, key);
            deStr = new String(deData, UTF8);
        } catch (Exception e) {
        } finally {
            deData = null;
            deByte = null;
        }
        return deStr;
    }

    private static byte[] encryptOrDecryptByte(byte[] bytes, int type, String strKey) {
        byte[] datas = null;
        Cipher cipher;
        try {
            Key key = getKey(strKey);
            if (key == null) {
                return bytes;
            }
            cipher = Cipher.getInstance(DES_ALGORITHM);
            cipher.init(type == ENCRYPT ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key);
            datas = cipher.doFinal(bytes);
        } catch (Exception e) {
        } finally {
            cipher = null;
        }
        return datas;
    }
}
